1025D - Recovering BST - CodeForces Solution


brute force dp math number theory trees *2100

Please click on ads to support us..

Python Code:

from math import gcd
import sys
readline=sys.stdin.readline


N=int(readline())
A=list(map(int,readline().split()))
graph=[0]*N
for i in range(N):
    for j in range(N):
        if gcd(A[i],A[j])>=2:
            graph[i]|=1<<j
dpL=[0 for l in range(N+1)]
dpR=[0 for l in range(N)]
for l in range(N):
    r=l+1
    dpL[r]|=1<<l
    dpR[l]|=1<<r
for i in range(2,N+1):
    for l in range(N+1-i):
        r=l+i
        x=(1<<r-l-1)-1
        if (graph[l]>>l+1)&(dpR[l+1]>>l+2)&(dpL[r]>>l+1)&x:
            dpL[r]|=1<<l
        if (graph[r-1]>>l)&(dpR[l]>>l+1)&(dpL[r-1]>>l)&x:
            dpR[l]|=1<<r
if dpR[0]>>1&dpL[N]&((1<<N)-1):
    ans="Yes"
else:
    ans="No"
print(ans)

C++ Code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;

const int mod=998244353;
const int N=705;
const int M=2;
 
bool f[N][N][M],cnm[N][N];
int a[N];

void run()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)	scanf("%d",&a[i]);
	for(int i=0;i<=n+1;i++)
		for(int j=0;j<=n+1;j++)
			if(__gcd(a[i],a[j])!=1)	cnm[i][j]=true;
	for(int i=1;i<=n;i++)
	{
		if(cnm[i][i-1])	f[i][i][0]=true;
		if(cnm[i][i+1])	f[i][i][1]=true;
	}
	for(int len=2;len<=n;len++)
	{
		for(int l=1;l+len-1<=n;l++)
		{
			int r=l+len-1;
			for(int k=l;k<r;k++)
			{
				f[l][r][0]|=(f[l][k][0]&f[k+1][r][0])|(f[l][r-1][1]&cnm[l-1][r]);
				f[l][r][1]|=(f[l][k][1]&f[k+1][r][1])|(f[l+1][r][0]&cnm[l][r+1]);
			}
		}
	}

	if(f[1][n][0]|f[1][n][1])	puts("Yes");
	else						puts("No");
}
 
int main()
{
	int T=1;
//	scanf("%d",&T);
	while(T--)	run(); 
	return 0;
}
/*

*/

 					 	 		 		 		 	  	 		 				


Comments

Submit
0 Comments
More Questions

14B - Young Photographer
143A - Help Vasilisa the Wise 2
320A - Magic Numbers
1658A - Marin and Photoshoot
514A - Chewbaсca and Number
382A - Ksenia and Pan Scales
734B - Anton and Digits
1080A - Petya and Origami
1642D - Repetitions Decoding
1440A - Buy the String
1658F - Juju and Binary String
478A - Initial Bet
981A - Antipalindrome
365A - Good Number
1204B - Mislove Has Lost an Array
1409D - Decrease the Sum of Digits
1476E - Pattern Matching
1107A - Digits Sequence Dividing
1348A - Phoenix and Balance
1343B - Balanced Array
1186A - Vus the Cossack and a Contest
1494A - ABC String
1606A - AB Balance
1658C - Shinju and the Lost Permutation
1547C - Pair Programming
550A - Two Substrings
797B - Odd sum
1093A - Dice Rolling
1360B - Honest Coach
1399C - Boats Competition